package com.rui.study.test.netty;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @program: study
 * @description:
 * @author: Yaowr
 * @create: 2019-03-25 14:20
 **/
public class Server {

    public static final Logger LOGGER = LoggerFactory.getLogger(Server.class);

    public static final int PORT = 5678;

    public static void doServer() {
        ServerBootstrap serverBootstrap = new ServerBootstrap();

        NioEventLoopGroup boss = new NioEventLoopGroup();
        NioEventLoopGroup worker = new NioEventLoopGroup();

        serverBootstrap
                .group(boss, worker)
                .channel(NioServerSocketChannel.class)
                .option(ChannelOption.SO_BACKLOG, 1024)
                .childOption(ChannelOption.SO_KEEPALIVE, true)
                .childOption(ChannelOption.TCP_NODELAY, true)
                .childHandler(new ChannelInitializer<NioSocketChannel>() {
                    @Override
                    protected void initChannel(NioSocketChannel nioSocketChannel) throws Exception {
                        nioSocketChannel.pipeline().addLast(new StringDecoder());
                        nioSocketChannel.pipeline().addLast(new SimpleChannelInboundHandler<String>() {
                            @Override
                            protected void channelRead0(ChannelHandlerContext channelHandlerContext, String s) throws Exception {
                                LOGGER.info("received: {}", s);
                            }
                        });
                    }
                })
                .bind(PORT)
                .addListener(future -> {
                    if (future.isSuccess()) {
                        LOGGER.info("server is succeed to bind: {}", PORT);
                    }
                });
        LOGGER.info("finished");
    }

    public static void main(String[] args) {
        doServer();
    }
}
